/**
 * https://dayjs.gitee.io/zh-CN/
 */
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween'
import 'dayjs/locale/zh-cn';
import relativeTime from 'dayjs/plugin/relativeTime';


const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const DATE_FORMAT = 'YYYY-MM-DD';


dayjs.locale('zh-cn');
dayjs.extend(relativeTime);
dayjs.extend(isBetween)


export function formatToDateTime(
  date: dayjs.Dayjs | string | undefined = undefined,
  format = DATE_TIME_FORMAT,
): string {
  return dayjs(date).format(format);
}

export function formatToDate(
  date: dayjs.Dayjs | string | undefined = undefined,
  format = DATE_FORMAT,
): string {
  return dayjs(date).format(format);
}

// 倒计时方法
export function countDown(endTime: string) {
  const endtime = dayjs(endTime).unix()
  const newtime = dayjs().unix()
  const totalSecond = endtime - newtime

  const d = Math.floor(totalSecond / 60 / 60 / 24)
  const h = Math.floor(totalSecond / 60 / 60 % 24)
  const m = Math.floor(totalSecond / 60 % 60)
  const s = Math.floor(totalSecond % 60)
  return {
    totalSecond, // 剩余总秒数
    d,
    h: h < 10 ? `0${h}` : h,
    m: m < 10 ? `0${m}` : m,
    s: s < 10 ? `0${s}` : s
  }
}

/**
 * @description 获取招呼语
 * @date 18/01/2024
 * @export
 * @param {string} dateTime // '2024/1/18 18:59'
 */
export function getGreetingMsg(dateTime?: string) {
  const date = dayjs(dateTime)

  const nowObj = {
    year: date.year(),
    month: date.month() + 1,
    date: date.date(),
  }
  const getDate = (h: string) => `${nowObj.year}-${nowObj.month}-${nowObj.date} ${h}`;
  const getResult = (startTime: string, endTime: string) =>
    date.isBetween(getDate(startTime), getDate(endTime), null, '[]');

  const data = [
    {
      startTime: '00:00',
      endTime: '5:59',
      text: '凌晨好!'
    },
    {
      startTime: '6:00',
      endTime: '8:59',
      text: '早上好!'
    },
    {
      startTime: '9:00',
      endTime: '11:59',
      text: '上午好!'
    },
    {
      startTime: '12:00',
      endTime: '18:59',
      text: '下午好!'
    },
    {
      startTime: '19:00',
      endTime: '23:59',
      text: '晚上好!'
    }
  ]

  for (let index = 0; index < data.length; index++) {
    const item = data[index];
    if (getResult(item.startTime, item.endTime)) {
      return item.text
    }
  }

  return ''
}

export const dateUtil = dayjs;
